<template>
  <view
      :style="{paddingBottom: safeBottom + 'px', backgroundImage: `url(${bgImage})` }"
      style="
        height: 100vh;
        background-color: #000;
        background-size: cover;
        background-repeat: no-repeat;
        background-position: center
      "
      v-if="dialogList.length > 0"
  >
    <!--    <view :style="{height: height + 'px'}"></view>-->
    <!-- 顶部自定义导航 -->
    <TnNavbar fixed alpha customBack :placeholder="false" bg-color="transparent" :bottom-shadow="false">
      <view slot="back" class='tn-custom-nav-bar__back'>
        <text class='icon tn-icon-left' style="font-size: 25rpx"></text>
        <text class='icon tn-icon-home-capsule-fill' style="font-size: 25rpx"></text>
      </view>
    </TnNavbar>
    <view
        @click="next"
        style="position: relative;height: 100vh"
    >
      <view
          v-if="showText"
          class="flex align-end justify-between padding-lr-xl"
          style="position: absolute; bottom: 0; left: 0;width: 100%;height: 100%"
      >
        <image
            v-for="(item, index) in characterPicture"
            :src="item"
            mode="heightFix"
            style="position:absolute;bottom: 0;"
            :style="{left: index * 50 + '%' }"
        ></image>
      </view>
      <view
          v-if="currentDialog.npc_name === '旁白'"
          class="flex align-center padding-lr-xl "
          :style="{paddingBottom: safeBottom + 'px'}"
          style="
            min-height: 25%;
            width: 100%;
            font-size: 17rpx;
            position: absolute;
            bottom: 0;
            left: 0;
            color: #b7cdfe;
            background-image: url(https://seerforwdw.info/seer-image/dialog/voiceover_dialog_box.png);
            background-repeat: no-repeat;
            background-size: cover;
          "
      >
        <view v-if="showText" style="width: 100%">
          <text
              class="char"
              :class="startTextAnimate ? 'char-animate' : 'char-stop'"
              :style="{'--index': index, }" v-for="(item, index) in currentDialog.dialog_arr">
            {{ item }}
          </text>
        </view>
      </view>
      <view
          v-else-if="currentDialog.npc_name === '漫画'"
          style="
            height: 100%;
            width: 100%;
            font-size: 17rpx;
            position: absolute;
            bottom: 0;
            left: 0;
            color: #b7cdfe;
            background-image: url(https://seerh5.61.com/resource/assets/mainLine/Dialog/map0.jpg);
            background-repeat: no-repeat;
            background-size: cover;
          "
      >
        <view style="position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%); width: 80%;height: 80%"
              class="flex flex-wrap">
          <view v-for="v in currentDialog.param.split('|')" style="width: 33%;height: 50%;padding: 5px">
            <image
                style="height: 100%"
                mode="heightFix"
                :src="`https://seerh5.61.com/resource/assets/mainLine/Dialog/${v.split(',')[0]}.png`"
            ></image>
          </view>
        </view>
        <view
            v-if="showText"
            style="
              width: 100%;
              position: absolute;
              bottom: 0;left: 0;
              min-height: 11%;
              font-size: 17rpx;
              color: #b7cdfe;
            "
            class="padding-lr-xl"
            :style="{paddingBottom: safeBottom + 'px'}"
        >
          <text
              class="char"
              :class="startTextAnimate ? 'char-animate' : 'char-stop'"
              :style="{'--index': index, }" v-for="(item, index) in currentDialog.dialog_arr">
            {{ item }}
          </text>
        </view>
      </view>
      <view
          v-else
          class="flex align-center padding-lr-xl"
          :style="{paddingBottom: safeBottom + 'px'}"
          style="
            min-height: 35%;
            width: 100%;
            font-size: 17rpx;
            position: absolute;
            bottom: 0;
            left: 0;
            color: #b7cdfe;
            background-image: url(https://seerforwdw.info/seer-image/dialog/npc_dialog_box.png);
            background-repeat: no-repeat;
            background-size: cover;
          "
      >
        <view
            style="
              position: absolute;
              top: -25rpx;
              left: 50rpx;
              width: 40vw;
              height: 40rpx;
              background-image: url(https://seerforwdw.info/seer-image/dialog/npc_name_box.png);
              background-repeat: no-repeat;
              background-size: cover;
              color: #fff;
            "
            class="flex align-center padding-left-sm"
        >
          {{ currentDialog.npc_name }}
        </view>
        <view v-if="showText" style="width: 100%">
          <text
              class="char"
              :class="startTextAnimate ? 'char-animate' : 'char-stop'"
              :style="{'--index': index, }" v-for="(item, index) in currentDialog.dialog_arr">
            {{ item }}
          </text>
        </view>
      </view>
      <image
          class="bouncing-element"
          src="/static/story/arrow.png"
          style="
              position: absolute;
              bottom: 8vh;
              right: 25rpx;
              transform: translateY(-50%);
              z-index: 10;
              width: 25px;
              height: 15px
            "
      ></image>
      <loading-page :show="showLoading" @click.stop=""/>
    </view>
  </view>
</template>

<script setup>
  import TnNavbar from "../../uni_modules/tuniaoui-vue3/components/navbar/src/navbar.vue";
  import LoadingPage from "../../components/loadingPage.vue";
  import {useUniAppSystemRectInfo} from "../../uni_modules/tuniaoui-vue3";
  import {getCurrentInstance, ref, watch} from "vue";
  import {onLoad, onUnload, onShareAppMessage} from '@dcloudio/uni-app'

  onShareAppMessage(() => {
    return {
      title: '剧情: ' + storyName.value,
      imageUrl: 'https://seerforwdw.info/seer-image/diduo.jpg',
      path:
          `/pagesA/story/animate?story_id=${storyId.value}&chapter_id=${chapterId.value}&name=${storyName.value}`
    }
  })

  const {height} = useUniAppSystemRectInfo().navBarInfo
  const safeBottom = ref(0)

  const {proxy} = getCurrentInstance()

  const showLoading = ref(false)

  const chapterId = ref(0)
  const storyId = ref(0)
  const storyName = ref('')

  const dialogList = ref([])

  const currentIndex = ref(0)
  const currentDialog = ref({})

  const showText = ref(true)
  const startTextAnimate = ref(true)
  const animateTimer = ref(null)

  // 背景音乐
  let bgMusic = null;

  // 背景图片
  const bgImage = ref('')

  // 人物图片
  const characterPicture = ref([])

  const setCurrentDialog = () => {
    showText.value = false
    startTextAnimate.value = true
    characterPicture.value = []
    currentDialog.value = dialogList.value[currentIndex.value]
    if (currentDialog.value.change_bgm) {
      bgMusic.src = 'https://seerh5.61.com/resource/assets/map/sound/' + currentDialog.value.change_bgm + '.mp3'
    }


    if (!currentDialog.value.param) {
      currentDialog.value.param = dialogList.value[currentIndex.value - 1].param
      dialogList.value[currentIndex.value].param = currentDialog.value.param
    }

    if (currentDialog.value.param) {
      let arr = currentDialog.value.param.split('|')
      if (currentDialog.value.param.indexOf('map') > -1) {
        bgImage.value = 'https://seerh5.61.com/resource/assets/mainLine/Dialog/' + arr[0].split(',')[0] + '.jpg'
      }
      arr.forEach(item => {
        if (item.indexOf('map') < 0 && item.indexOf('mh') < 0) {
          let url = 'https://seerh5.61.com/resource/assets/mainLine/Dialog/' + item.split(',')[0] + '.png'
          characterPicture.value.push(url)
        }
      })
    }
    console.log(currentDialog.value);
    showText.value = true
    animateTimer.value = setTimeout(() => {
      startTextAnimate.value = false
      clearTimeout(animateTimer.value)
    }, 100 * currentDialog.value.dialog_arr.length)
  }

  const handleGetAdventureStoryDialog = async () => {
    showLoading.value = true
    dialogList.value = await proxy.$api.getAdventureStoryDialog({
      id: storyId.value,
      chapter_id: chapterId.value,
      sort: 'index',
      order: 'asc'
    })
    showLoading.value = false
    setCurrentDialog()
  }

  const next = () => {
    if (startTextAnimate.value) {
      startTextAnimate.value = false
      clearTimeout(animateTimer.value)
    } else {
      if (currentIndex.value < dialogList.value.length - 1) {
        currentIndex.value++
      }else {
        uni.showModal({
          title: '提示',
          content: '剧情已结束~',
          showCancel: false,
          success: res => {
            if(res.confirm) {
              uni.navigateBack()
            }
          }
        })
      }
    }
  }

  onLoad(async (res) => {
    chapterId.value = Number(res.chapter_id)
    storyId.value = Number(res.story_id)
    storyName.value = res.name
    bgMusic = uni.createInnerAudioContext()
    bgMusic.autoplay = true
    bgMusic.loop = true;
    bgMusic.volume = 0.2
    await handleGetAdventureStoryDialog()
  })

  onUnload(() => {
    bgMusic.stop()
  })

  watch(() => currentIndex.value, () => {
    setCurrentDialog()
  })
</script>

<style scoped lang="scss">
  image {
    width: auto;
  }

  :deep(.tn-navbar-back__multi__item) {
    font-size: 20rpx !important;
  }

  @keyframes bounce {
    0%, 100% {
      transform: translateY(0); /* 初始和结束位置 */
    }
    50% {
      transform: translateY(-5px); /* 中间位置，向上移动 20px */
    }
  }

  .bouncing-element {
    display: inline-block; /* 保证元素是块级的 */
    animation: bounce 1s infinite; /* 应用动画，1s 循环 */
  }

  .char {
    opacity: 0;
  }

  .char-animate {
    animation: fadeIn 1s forwards;
    animation-delay: calc(var(--index) * 0.1s);
  }

  .char-stop {
    opacity: 1
  }

  @keyframes fadeIn {
    100% {
      opacity: 1;
    }
  }
</style>
